<template>
  <div class="slider">
    <div class="slider-container" ref="container">
      <img v-for="item in imgs" :key="item.targetId" :src="item.imageUrl" alt="轮播">
    </div>
  </div>
</template>

<script>
import { ref, getCurrentInstance, onMounted, reactive, onUnmounted } from 'vue'
export default {
  setup() {
    const imgs = ref([])
    const container = ref()
    const data = reactive({
      curIndex: 0
    })
    let timer
    // 请求数据
    const { proxy } = getCurrentInstance()
    proxy.$http
      .get('/banner')
      .then(res => {
        // console.log(res.banners)
        imgs.value = res.banners
      })
      .catch(err => {
        console.log(err)
      })

    // 添加动画
    onMounted(() => {
      timer = setInterval(() => {
        data.curIndex++
        animation()
      }, 3000)
    })

    onUnmounted(() => {
      timer = clearInterval(timer)
    })

    // 动画
    const animation = () => {
      let left = `-${7.5 * (data.curIndex % imgs.value.length)}rem`
      container.value.style.left = left
    }

    return {
      imgs,
      container
    }
  }
}
</script>

<style scoped>
.slider {
  width: 7.5rem;
  height: 2.8rem;
  margin-top: 0.2rem;
  position: relative;
  overflow: hidden;
}

.slider-container {
  position: absolute;
  left: 0;
  width: 75rem;
  height: 2.8rem;
  /* left: -7.5rem; */
  transition: all 0.5s linear;
}

.slider-container img {
  border-radius: 0.2rem;
  width: 7.5rem;
}
</style>